package com.heartech.prediciton_wx.controller.material;

import com.heartech.prediciton_wx.service.media.MediaService;
import com.heartech.prediciton_wx.utils.token.AccessTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;


@Slf4j
@RestController
@RequestMapping("/wxpublic")
public class GetMaterialController {
    @Autowired
    private MediaService mediaService;

    @GetMapping("/media_download")
    public ResponseEntity<String> mediaDownload() {
        String accessToken = AccessTokenUtil.getAccessToken();
        String mediaId = mediaService.getMediaId();

        if (accessToken != null) {
            String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaId;

            try {
                URL obj = new URL(url);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                con.setRequestMethod("GET");

                int responseCode = con.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 从响应头获取文件名
                    String headerField = con.getHeaderField("Content-disposition");
                    String fileName = headerField.substring(headerField.indexOf("\"") + 1, headerField.lastIndexOf("\""));

                    // 创建文件夹和文件路径
                    String currentDir = System.getProperty("user.dir");
                    String folderPath = currentDir + File.separator + "imgs";
                    String filePath = folderPath + File.separator + fileName;

                    File folder = new File(folderPath);
                    if (!folder.exists()) {
                        folder.mkdirs(); // 创建目录及其父目录
                    }

                    // 将输入流写入文件
                    try (InputStream inputStream = con.getInputStream();
                         FileOutputStream outputStream = new FileOutputStream(filePath)) {

                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }

                    log.info("Media download successful, Response Code: " + responseCode);
                    String response = "{\"message\":\"Media download successful\", \"responseCode\": " + responseCode + "}";
                    return ResponseEntity.ok(response);
                } else {
                    log.error("Media download request not worked, Response Code: " + responseCode);
                    String errorResponse = "{\"message\":\"Media download request not worked\", \"responseCode\": " + responseCode + "}";
                    return ResponseEntity.status(responseCode).body(errorResponse);
                }
            } catch (IOException e) {
                log.error("Error in media download", e);
            }
        } else {
            log.error("Failed to get access_token");
        }
        return null;
    }
}


